﻿#include "LuaHelper.h"

#include "lua.hpp"

#include <QDebug>

LuaHelper* LuaHelper::m_instance = new LuaHelper;

class LuaHelperPrivate : public QObject{
public:
    LuaHelperPrivate(LuaHelper* lua_)
        : lua_hs(lua_)
        ,L(luaL_newstate())
    {
        luaL_openlibs(L);
    }
    ~LuaHelperPrivate(){
        if(L){
            lua_close(L);
        }
    }

    LuaHelper* lua_hs;
    lua_State* L;
};


LuaHelper::LuaHelper()
    :d(new LuaHelperPrivate(this))
{

}

LuaHelper::~LuaHelper()
{
    if(d)
        delete d;
}

LuaHelper *LuaHelper::getInstance()
{
    if(m_instance)
        return m_instance;
    return nullptr;
}

void LuaHelper::freeInstance()
{
    if(m_instance)
        delete m_instance;
}

bool LuaHelper::loadLuaModel(const QString &filePath)
{
    if (luaL_dofile(d->L, filePath.toStdString().c_str())) {
        const char* error = lua_tostring(d->L, -1); // 获取错误信息
        qDebug() << "Error loading Lua script: " << error;
        lua_pop(d->L, 1); // 弹出错误信息
        return false;
    }
    return true;
}

QMap<uint32_t, QString> LuaHelper::execDictionary()
{
    lua_getglobal(d->L, "DictionaryMap");

    if (!lua_istable(d->L, -1)) {
        qDebug() << "DictionaryMap is not a table";
        return QMap<uint32_t,QString>();
    }


    QMap<uint32_t,QString> t;
    // 初始化遍历
    lua_pushnil(d->L);
    while (lua_next(d->L, -2) != 0) {
        // 键，字符串
        QString key = QString::fromStdString(lua_tostring(d->L, -2));
        // 值，无符号整数
        uint32_t value = lua_tointeger(d->L, -1);  // 值（布尔值）

        t[value] = key;

        lua_pop(d->L, 1);  // 移除值，保留键
    }

    return t;
}

QVariant LuaHelper::execLua(int type, double base, double quantity)
{
    lua_getglobal(d->L, "LuaFunctionTypeManage");


    lua_pushinteger(d->L, type);
    lua_pushinteger(d->L, base);
    lua_pushinteger(d->L, quantity);

    if (lua_pcall(d->L, 3, 1, 0) != LUA_OK) {
        qDebug() << "Error calling Lua function: " << lua_tostring(d->L, -1);
        return QVariant();
    }

    // 获取返回值
    if (lua_isnumber(d->L, -1)) {
        double result = lua_tonumber(d->L, -1);
        return QVariant(result);
        qDebug() << "Arithmetic_operation value: " << result;
    }

    if (lua_isstring(d->L, -1)) {
        const char* result = lua_tostring(d->L, -1);
        return QVariant(result);
        qDebug() << "Quantized value: " << result;
    }
    return QVariant();
}

bool LuaHelper::execLuaWithMathFormula(double base, const char *mathFormula, QVariant& result)
{
    lua_getglobal(d->L, "LuaFuntionParserMathFormula");

    lua_pushinteger(d->L, base);
    lua_pushstring(d->L, mathFormula);

    if (lua_pcall(d->L, 2, 1, 0) != LUA_OK) {
        result = lua_tostring(d->L, -1);
        return false;
    }

    // 获取返回值
    if (lua_isnumber(d->L, -1)) {
        result = lua_tonumber(d->L, -1);
        return true;
    }
    else
    {
        result = lua_tostring(d->L, -1);
        return false;
    }
}

